<template>
    <el-row>
        <el-col :span="3"></el-col>
        <el-col :span="12">
            <el-row class="content-back" style="padding: 10px;">
                <el-link @click="toCategory">{{ plant.categoryName }}</el-link>
                <el-text v-if="plant.familyName"> >> </el-text>
                <el-link>{{ plant.familyName }}</el-link>
                <el-text v-if="plant.genusName"> >> </el-text>
                <el-link>{{ plant.genusName }}</el-link>
                <el-text v-if="plant.plantSpecific"> >> </el-text>
                <el-link>{{ plant.plantSpecific }}<span v-if="plant.latinName" style="margin-left: 3px;">{{ plant.latinName }}</span></el-link>
            </el-row>
            <el-row class="content-back" style="padding: 20px 20px 5px 20px">
                <img :src="showImg" style="width: 100%;height: 650px;" />
                <div style="margin-top: 10px;margin-left: 250px;">
                    <div style="margin-right: 10px;display: inline;">
                        <el-image title="点踩" style="cursor: pointer;" @click="toUnlike" :src="unlikeImg"></el-image>
                        <el-text style="bottom: 7px;position: relative;">12</el-text>
                    </div>
                    <div style="margin-right: 10px;display: inline;">
                        <el-image title="点赞" style="cursor: pointer;" @click="toLike" :src="likeImg"></el-image>
                        <el-text style="bottom: 7px;position: relative;">572813</el-text>
                    </div>
                    <div style="display: inline;">
                        <el-image title="收藏" style="cursor: pointer;" @click="toCollect" :src="collectImg"></el-image>
                        <el-text style="bottom: 7px;position: relative;">121</el-text>
                    </div>

                </div>
            </el-row>
        </el-col>
        <el-col :span="6">
            <el-row class="content-back">
                <el-col :span="24" style="padding: 10px;">
                    <el-carousel :interval="4000" type="card" height="120px">
                        <el-carousel-item v-for="item in plant.plantPictures">
                            <img @click="cutImg(item.plantPicture)" :src="item.plantPicture"
                                style="width: 100%;height: 120px;">
                        </el-carousel-item>
                    </el-carousel>
                </el-col>
            </el-row>
            <el-row class="content-back" style="padding: 10px;max-height: 430px;height: 430px;">

                <div style="display: flex;">
                    <el-avatar :src="plant.userPhoto" :size="50"></el-avatar>
                    <div style="margin-left: 10px;margin-top: 15px;">
                        <el-text>{{ plant.userName }}</el-text>
                        <el-text size="small" style="margin-left: 15px;">{{ formatterDate(plant.userCreateTime) }}</el-text>
                    </div>
                </div>
                <div>
                    <el-text>拍摄于：{{ plant.address }}</el-text>
                </div>
                <div>
                    <el-text>上传时间：{{ formatterDate(plant.createTime) }}</el-text>
                </div>
                <div style="display: flex;width: 100%;margin-top: 5px;"
                    v-if="collegePlantId && store.useUserStore.user.userRole == 2">
                    <el-tag type="success">
                        <el-icon>
                            <School />
                        </el-icon>
                        {{ collegeName }}
                        <el-text style="margin-left: 10px;" size="small">{{ collegeAddress }}</el-text>
                    </el-tag>
                </div>
                <el-divider />
                <div style="line-height: 24px;">
                    <el-text tag="b">{{ plant.plantName }}</el-text>
                    <el-text style="text-indent: 24px;" tag="p">{{ plant.plantDescription }}</el-text>
                </div>
                <div style="margin-top: 5px;width: 100%;" v-if="store.useUserStore.user.userId === plant.userId">
                    <el-button v-if="store.useUserStore.user.userRole === 2" style="float: left;" type="success"
                        @click="collegeWorks">校园认证</el-button>
                    <el-button type="primary" @click="updateWorks">修改作品</el-button>
                    <el-popconfirm confirm-button-text="确定" cancel-button-text="返回" :icon="InfoFilled" icon-color="#626AEF"
                        title="确定要删除该作品吗?" @confirm="removeWorks">
                        <template #reference>
                            <el-button type="danger">删除作品</el-button>
                        </template>
                    </el-popconfirm>

                </div>
            </el-row>
            <el-row class="content-back" style="padding: 10px;">
                <!-- <el-text>发表评论</el-text> -->
                <el-input v-model="commentForm.commentContent" resize="none" rows="4" placeholder="请发表友善评论"
                    type="textarea" />
                <el-button @click="addComment" style="margin-top: 5px;margin-left: 242px;">发表评论</el-button>
            </el-row>
        </el-col>
        <el-col :span="3"></el-col>
    </el-row>
    <el-row>
        <el-col :span="3"></el-col>
        <el-col :span="18">
            <div style="margin: 10px;padding: 10px;background-color: #fff;">
                <div style="margin-bottom: 20px;font-weight: bold;">评论区</div>
                <PlantComment :plantId="plantId"></PlantComment>
            </div>

        </el-col>
        <el-col :span="3"></el-col>
    </el-row>

    <el-drawer v-model="drawerUpdate" title="修改作品" :direction="'rtl'">
        <UpdatePlant :plantInfo="plant"></UpdatePlant>
    </el-drawer>

    <el-drawer v-model="drawerCollege" title="校园认证" size="25%" :direction="'rtl'">
        <el-form-item style="margin-top: 250px;" required>
            <el-text v-show="collegeAddress">请输入校园内详细地址</el-text>
        </el-form-item>
        <el-form-item required>
            <el-input v-model="collegePlant.collegeAddress" placeholder="请输入校园内详细地址"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button v-if="collegeAddress" @click="toCollegeSave" style="margin-left: 120px;"
                type="success">确认修改</el-button>
            <el-button v-else style="margin-left: 120px;" @click="toCollegeSave" type="success">确认认证</el-button>
        </el-form-item>
    </el-drawer>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { onMounted, reactive, ref, watch } from 'vue';
import { usePlantDetailApi, useRemovePlantApi } from '@/api/plant/plant';
import { useCollegePlantInfoApi, useCollegePlantSaveApi } from '@/api/college/college';
import { InfoFilled, Refresh, School } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import UpdatePlant from './UpdatePlant.vue';
import store from '@/stores';
import PlantComment from '../comment/PlantComment.vue';
import { useSaveCommentApi } from '@/api/comment/comment'

const route = useRoute();
const router = useRouter();
const plantId = route.params.id
const plant = reactive({
    plantId: '',
    plantName: '',
    plantSpecific: '',
    latinName: '',
    categoryId: '',
    familyId: '',
    plantDescription: '',
    address: '',
    plantPicture: '',
    userId: '',
    createTime: '',
    isChoiceness: 0,
    categoryName: '',
    familyName: '',
    genusName: '',
    genusId: '',
    userName: '',
    userCreateTime: '',
    userPhoto: '',
    plantPictures: [{
        plantPicture: '',
        pictureIntro: ''
    }]
});
const collegePlant = reactive({
    plantId: "",
    collegeId: "",
    userId: "",
    collegeAddress: ""
})
const commentForm = reactive({
    plantId: plantId,
    userId: "",
    commentContent: ""
})

const showImg = ref()
const drawerUpdate = ref(false)
const drawerCollege = ref(false)
const likeImg = ref('/images/like1.svg')
const unlikeImg = ref('/images/unlike1.svg')
const collectImg = ref('/images/collect1.svg')

const collegePlantId = ref()
const collegeAddress = ref()
const collegeName = ref()

onMounted(async () => {
    const { data } = await usePlantDetailApi(plantId)
    if (data) {
        Object.assign(plant, data)
        document.title = plant.plantName + ' | Share Plant'
    } else {
        router.push({ name: '404' })
    }
    showImg.value = plant.plantPicture

    const { data: info } = await useCollegePlantInfoApi(plantId)
    if (info) {
        collegePlantId.value = info.id
        collegeName.value = info.collegeName
        collegeAddress.value = info.collegeAddress
    }
    if (store.useUserStore.user.userRole == 2) {
        collegePlant.userId = plant.userId
        collegePlant.plantId = plant.plantId
        collegePlant.collegeId = store.useUserStore.user.collegeId
    }
})

const updateWorks = () => {
    drawerUpdate.value = true
}
const collegeWorks = () => {
    collegePlant.collegeAddress = collegeAddress.value
    drawerCollege.value = true
}
const removeWorks = async () => {
    await useRemovePlantApi(plant).then(() => {
        ElMessage({
            message: '删除成功',
            type: 'success'
        })
        router.replace({ path: '/category' })
    })
}

const cutImg = (val: string) => {
    showImg.value = val
}

const toCollegeSave = async () => {
    await useCollegePlantSaveApi(collegePlant).then(() => {
        ElMessage({
            message: "认证成功",
            type: "success"
        })
        refresh()
    })
}

const toLike = () => {
    if (likeImg.value == '/images/like1.svg') {
        likeImg.value = '/images/like2.svg'
    } else {
        likeImg.value = '/images/like1.svg'
    }
}
const toUnlike = () => {
    if (unlikeImg.value == '/images/unlike1.svg') {
        unlikeImg.value = '/images/unlike2.svg'
    } else {
        unlikeImg.value = '/images/unlike1.svg'
    }
}
const toCollect = () => {
    if (collectImg.value == '/images/collect1.svg') {
        collectImg.value = '/images/collect2.svg'
    } else {
        collectImg.value = '/images/collect1.svg'
    }
}

const toCategory = () => {
    sessionStorage.setItem("navigation_index", '2')
    router.push({ name: 'Category', query: { categoryId: plant.categoryId } })
}

const addComment = async () => {
    if (store.useUserStore.user.userId) {
        commentForm.userId = store.useUserStore.user.userId
        await useSaveCommentApi(commentForm).then(() => {
            ElMessage({
                type: 'success',
                message: '评论成功'
            })
            refresh()
        })
    } else {
        ElMessage({
            type: 'warning',
            message: '请先登录'
        })
    }

}

const formatterDate = (val: string) => {
    let newDateObj = new Date(val)
    let year = newDateObj.getFullYear()
    let month: string | number = newDateObj.getMonth() + 1
    let day: string | number = newDateObj.getDate()
    let hh: string | number = newDateObj.getHours()
    let mm: string | number = newDateObj.getMinutes()
    let ss: string | number = newDateObj.getSeconds()
    month = month > 9 ? month : '0' + month
    day = day > 9 ? day : '0' + day
    hh = hh > 9 ? hh : '0' + hh
    mm = mm > 9 ? mm : '0' + mm
    ss = ss > 9 ? ss : '0' + ss
    return `${year}/${month}/${day} ${hh}:${mm}:${ss}`
}

function refresh() {
    // 刷新当前路由
    const { fullPath } = route
    router.replace({
        path: '/redirect' + fullPath
    })
}

</script>

<style scoped lang="scss">
.content-back {
    background-color: #fff;
    margin: 10px;
}


.el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
    background-color: #d3dce6;
}
</style>